package com.ycode.bang.anbang.baseui;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.orhanobut.logger.Logger;
import com.ycode.bang.anbang.MyApp;
import com.ycode.bang.anbang.R;
import com.ycode.bang.anbang.utils.MyLog;
import com.ycode.bang.anbang.utils.MyStringRequest;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;


/**
 * @author:ken
 * @date:2016/3/24
 * @todo:Fragment基类
 */
public abstract class BaseFragment<T> extends Fragment {
    private   String TAG = this.getClass().getSimpleName();
    private String title;
    private int iconId;
    protected TreeMap<String, String> headers = new TreeMap<>();

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public int getIconId() {
        return iconId;
    }

    public void setIconId(int iconId) {
        this.iconId = iconId;
    }
    protected Bundle bundle;

    private boolean bool = true;
    private Bitmap bitmap;

    protected ProgressDialog progressDialog;
    protected String progressString;
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        MyLog.e(TAG,"come to "+TAG);
        View view = inflater.inflate(R.layout.fragment, null, false);
        TextView textView = (TextView) view.findViewById(R.id.text);
        textView.setText(getTitle());
        return view;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        headers.put("Custom-Auth-Key", "uKohUYb61miytTSo5bv3lQ__");
        super.onCreate(savedInstanceState);
        bundle = new Bundle();

        progressString = getResources().getString(R.string.waiting);
    }

    protected boolean isVisible;

    /**
     * 在这里实现Fragment数据的缓加载.
     *
     * @param isVisibleToUser
     */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (getUserVisibleHint()) {
            isVisible = true;
            onVisible();
        } else {
            isVisible = false;
            onInvisible();
        }
    }


    protected void onVisible() {

    }


    protected void onInvisible() {

    }


    @Override
    public void onStop() {
        super.onStop();
        //关闭请求
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    public void jumpIntoOtherUI(Context context,Class<?> cls) {
        Intent intent = new Intent(context, cls);
        if(cls.toString().equals("LoginActivity.class")){
            intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        }
        intent.putExtras(bundle);
        context.startActivity(intent);
        // overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
    }

    protected void toast(CharSequence hint,Context context) {
        Toast.makeText(context, hint, Toast.LENGTH_SHORT).show();
    }

    protected void getHttpGetRequest(String url, final Class<T> cls, final int flag,
                                     String...str){
        final String uri = getUrl(url, str);
        Logger.d(uri);
        StringRequest stringRequest = new StringRequest(uri, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (progressDialog!=null){
                    progressDialog.dismiss();
                }
                com.orhanobut.logger.Logger.d(uri, response.toString());
                Gson gson = new Gson();
                T object = (T) gson.fromJson(response.toString(), cls);// 得到对象
                Message message = new Message();
                message.obj = object;
                message.arg1 = flag;
                handler.sendMessage(message);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if (progressDialog!=null){
                    progressDialog.dismiss();
                }
                if (error.getMessage() != null) {
                    Log.e("VolleyError", error.getMessage(), error);
                }
            }
        });

        //请求加上Tag,用于取消请求
        stringRequest.setTag(flag);
        MyApp.instance.mRequestQueue.add(stringRequest);
    }

    protected void getHttpPostRequest( final String url, final Class<T> cls, final int flag,
                                       String...
            strings) {

        Map<String, String> param = new HashMap<String, String>();
        for(int i=0;i<strings.length;i +=2){
            param.put(strings[i], strings[i+1]);
        }
        MyStringRequest jr = new MyStringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {

                    @Override
                    public void onResponse(String response) {
                        if (progressDialog!=null){
                            progressDialog.dismiss();
                        }
                        // TODO Auto-generated method stub
                        com.orhanobut.logger.Logger.d(url,response.toString());
                        Gson gson = new Gson();
                        T object = (T) gson.fromJson(response.toString(), cls);// 得到对象
                        Message message = new Message();
                        message.obj = object;
                        message.arg1 = flag;
                        handler.sendMessage(message);
                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                // TODO Auto-generated method stub
                if (progressDialog!=null){
                    progressDialog.dismiss();
                }
                if (error.getMessage() != null) {
                    Log.e("VolleyError", error.getMessage(), error);
                }
            }
        }, param);
        //请求加上Tag,用于取消请求
        jr.setTag(flag);
        MyApp.instance.mRequestQueue.add(jr);
    }

    protected void getHttpPutRequest( String url, final Class<T> cls, final int flag, String...
            strings) {

        final String uri = getUrl(url, strings);
        StringRequest stringRequest = new StringRequest(Request.Method.PUT,uri, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (progressDialog!=null){
                    progressDialog.dismiss();
                }
                com.orhanobut.logger.Logger.d(uri,response.toString());
                Gson gson = new Gson();
                T object = (T) gson.fromJson(response.toString(), cls);// 得到对象
                Message message = new Message();
                message.obj = object;
                message.arg1 = flag;
                handler.sendMessage(message);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                failedHttp(error);
                if (progressDialog!=null){
                    progressDialog.dismiss();
                }
                if (error.getMessage() != null) {
                    Log.e("VolleyError", error.getMessage(), error);
                }
            }
        });

        //请求加上Tag,用于取消请求
        stringRequest.setTag(flag);
        MyApp.instance.mRequestQueue.add(stringRequest);
    }

    protected abstract void getSuccessRequest(T response,int flag);

    android.os.Handler handler = new android.os.Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            getSuccessRequest((T) msg.obj, msg.arg1);
        }
    };

    public String getUrl(String url, String... objects) {

        if (objects != null) {
            url = url + "?";
            for (int i = 0; i < objects.length; i = i + 2) {
                String tempString = null;
                try {
                    tempString = URLEncoder.encode(objects[i + 1], "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                url = url + objects[i] + "=" + tempString;
                if (i != objects.length - 2) {
                    url = url + "&";
                }
            }
        }
        return url;
    }

    protected void failedHttp(VolleyError error){

    }
}